package cn.sun.basic.controller;

import cn.sun.basic.util.AjaxResult;
import cn.sun.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * fastdfs接口控制器
 *    上传
 *    删除
 *    修改=删除+上传
 *    查询：http:8888
 */
@RestController
@RequestMapping("/fastDfs")
public class FastdfsController {

    //@RequestPart文件上传
    //required = true 必传
    // value = "file" 传过来值名称
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            String fileName = file.getOriginalFilename(); //获取文件名 xxx.jpg
            String extName = fileName.substring(fileName.indexOf(".")+1); //jpg
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败!"+e.getMessage());
        }

    }


    //(@RequestParam ===> ?xxx=yyyy

    /*
    /group1/M00/00/00/rBEAA1-zcq6AeErUAAVeAmihutw009.jpg
    group1
    M00/00/00/rBEAA1-zcq6AeErUAAVeAmihutw009.jpg
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){ //
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);
            FastDfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!"+e.getMessage());
        }

    }
}
